package com.zry.traced.presenter

import android.content.Intent
import android.view.View
import com.zry.traced.MainActivity
import com.zry.traced.R
import com.zry.traced.been.HttpResponse
import com.zry.traced.been.LoginInfoBean
import com.zry.traced.retrofit.ShowUserView
import com.zry.traced.ui.activity.LoginActivity
import com.zry.traced.utils.ACacheUtil
import com.zry.traced.utils.ToastUtil
import com.zry.traced.utils.ToastUtil.Companion.toast
import kotlinx.android.synthetic.main.activity_login.*


/**
 * Created by zry on 2017/9/6.
 */

class LoginPresenter(private val activity: LoginActivity) : ShowUserView {


    fun loginHandlerClick(view: View) {
        when (view.id) {
            R.id.deletePassword -> {
                activity.loginAccount.setText("")
            }
            R.id.loginBtn -> {
                getEditString()
                loginApi(activity.loginAccount.text.toString().trim(), activity.loginPassword.text.toString().trim())
            }
        }
    }


    fun getEditString() {
        if (activity.loginAccount.text.toString() == "") {
            toast(activity, "账号不能为空")
            return
        }
        if (activity.loginPassword.text.toString() == "") {
            toast(activity, "密码不能为空")
            return
        }
    }
    fun loginApi(username: String, password: String) {
        HttpServer(this).loginApi(username, password,"2", activity)
    }
    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            0 -> {
                val httpResponse: HttpResponse<LoginInfoBean> = data as HttpResponse<LoginInfoBean>
                if (httpResponse.State == "1") {
                    ACacheUtil().setLoginInfo(httpResponse.ResultData)
                    ACacheUtil().setUsername(activity.loginAccount.text.toString().trim())
                    ACacheUtil().setPassword(activity.loginPassword.text.toString().trim())
                    val intent = Intent(activity, MainActivity::class.java)
                    activity.startActivity(intent)
                } else {
                    ToastUtil.toast(activity, httpResponse.Message)
                }
            }
        }
    }

}
